package com.weixin.project.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class HttpService {
    @Autowired
    RestTemplate restTemplate;
    private HttpHeaders headers(){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        return headers;
    }

    public JSONObject sendGETRequest(String baseUrl, Map<String, Object> params){
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl);
        for (Map.Entry<String, Object> entry: params.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof List) {
                List<?> listValue = (List<?>) value;
                for (Object item : listValue) {
                    builder.queryParam(entry.getKey(), item);
                }
            } else if (value instanceof Set) {
                Set<?> setValue = (Set<?>) value;
                for (Object item : setValue) {
                    builder.queryParam(entry.getKey(), item);
                }
            } else {
                builder.queryParam(entry.getKey(), value);
            }
        }
        String url = builder.toUriString();
        System.out.println("sending GET request to " + url + " ...");
        HttpEntity<String> entity = new HttpEntity<>("parameters", headers());
        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                JSONObject.class);
        JSONObject body = responseEntity.getBody();
        System.out.println("response:");
        System.out.println(body);
        return body;
    }

    public JSONObject sendPostRequest(String url, Object body) {
        System.out.println("sending POST request to " + url + " ...");
        HttpEntity<Object> requestEntity = new HttpEntity<>(body, headers());
        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                JSONObject.class);
        JSONObject responseBody = responseEntity.getBody();
        System.out.println("response:");
        System.out.println(responseBody);
        return responseBody;
    }
}
